
#include <QtDebug>
#include <QFile>
#include <QTextStream>
#include <QRegExp>

#include <QStringList>

#include "mac.h"

#ifdef Q_OS_LINUX
#include <arpa/inet.h>
#endif


QString MAC_Addr::get_mac()
{

#ifdef Q_OS_LINUX
	QString gwip, line;
	QRegExp rx;
	char buf[1024], iface[16];
	int iflags, metric, refcnt, use, mss, window, irtt;
	unsigned long gate_addr=0, mask_addr, net_addr;
	struct in_addr myaddr;

	FILE *fp = fopen("/proc/net/route", "r");

	if (!fp) {
		return NULL;
	}

	fgets(buf,1023,fp);

	while (fgets(buf, 1023, fp)) {
		sscanf(buf, "%16s %lX %lX %X %d %d %d %lX %d %d %d\n",
		       iface, &net_addr, &gate_addr,
	 		&iflags, &refcnt, &use, &metric, &mask_addr,
  			&mss, &window, &irtt);

		if (net_addr != 0)
			continue;

		myaddr.s_addr = gate_addr;
		gwip = inet_ntoa(myaddr);
		fclose(fp);
		break;
	}

	if (gwip == NULL)
		return NULL;

	QFile arpFile("/proc/net/arp");

	if (arpFile.exists() == FALSE) {
		return NULL;
	}

	if (arpFile.open(QIODevice::ReadOnly) == FALSE) {
		return NULL;
	}

	QTextStream t(&arpFile);

	while((line = t.readLine()) != NULL) {
		if (line.indexOf(gwip, 0) != -1) {
			rx.setPattern("[ ]+");
			QString gwMAC = line.section(rx, 3, 3);
			arpFile.close();
			return gwMAC;
		}
	}
	arpFile.close();
	return NULL;
#else
	return NULL;
#endif

	
}


